import { useInfiniteScroll } from '@vueuse/core'
import type { List } from './index.d'

export default function (element: Ref<HTMLDivElement>) {
	let requesting = true
	const list = ref<List[]>([])
	const params = { page: 1, limit: 20 }

	const {
		data,
		loading,
		runAsync: fetchList
	} = useAxios<List[]>({
		params,
		url: urls.fetchList,
		config: { abort: false },
		onSuccess() {
			requesting = false
			params.page++
			list.value = [...list.value, ...data.value]
		}
	})

	useInfiniteScroll(
		element,
		() => {
			if (!requesting) fetchList()
		},
		{ distance: 20, interval: 1500 }
	)

	return { list, loading }
}
